package com.yjy;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicLong;

public class MainTest {

// 创建线程池
private static final AtomicLong count = new AtomicLong(0L);
private static final ThreadFactory factory = r -> {
    Thread thread = new Thread(r, String.format("check-thread-%d", count.getAndIncrement()));
    // 设置异常捕获，executorService.execute()才会打印，executorService.submit()不会打印以下信息
    thread.setDefaultUncaughtExceptionHandler((t, e) -> System.out.println(String.format("线程%s抛出异常：%s", t.getName(), e.getMessage())));
    return thread;
};
private static final ExecutorService executorService = new ThreadPoolExecutor(10, 20, 100L, TimeUnit.SECONDS, new LinkedBlockingQueue<>(100),
        factory, new ThreadPoolExecutor.CallerRunsPolicy());

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        executorService.execute(() -> {
            System.out.println("线程池" + Thread.currentThread().getName() + "执行任务1");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            int i = 10 / 0;
        });

        executorService.submit(() -> {
            System.out.println("线程池" + Thread.currentThread().getName() + "执行任务2");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            int i= 20 / 0;
        });

        System.out.println("main线程执行任务");

        Thread.sleep(3000);
    }
}
